# -*- coding:utf-8 -*-


class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None and l2 is None:
            return
        head = ListNode(0)
        point = head
        carry = 0

        while l1 is not None and l2 is not None:
            sum = l1.val+l2.val+carry
            point.next = ListNode(sum%10)
            carry = sum/10
            sum = 0
            point = point.next
            l1 = l1.next
            l2 = l2.next

        while l1 is not None:
            sum = l1.val+carry
            point.next = ListNode(sum%10)
            carry = sum/10
            point = point.next
            l1 = l1.next
        
        while l2 is not None:
            sum = l2.val+carry
            point.next = ListNode(sum%10)
            carry = sum/10
            point = point.next
            l2 = l2.next

        if carry is not 0:
            point.next = ListNode(carry)
        
        return head.next



if __name__ == "__main__":
    h1 = ListNode(2)
    h2 = ListNode(5)
    l1 = h1
    l2 = h2
    l1.next = ListNode(4)
    l2.next = ListNode(6)
    l1, l2 = l1.next, l2.next

    l1.next = ListNode(3)
    l2.next = ListNode(4)
    l1, l2 = l1.next, l2.next

    solution = Solution()
    h = solution.addTwoNumbers(h1, h2)

    while h is not None:
        print h.val
        h = h.next
